State 的資料結構跟 Props 一樣,只是一個 JavaScript Object,且他們的變化都會觸發渲染更新,那要怎麼分辨呢?
props:
properties(屬性)的縮寫,主要職責是在 React 元件中傳遞資料,不過在 React 元件中傳遞數據的資料僅能父層到子層(單向)。
state:
是 React 特殊的內建 Object,可以在元件中創建以及管理自己的數據,不同於 props 元件傳遞數據是不能透過 state 的
也就是說
porps⇒不可以修改,只能讀資料
state⇒是可以修改的
props:
class ParentComponent extends Component {
    render() {
        return (
            <ChildComponent name="First Child" />
        );
    }
}
const ChildComponent = (props) => {
    return <p>{props.name}</p>;
};
state:
class StateTest extends React.Component {
    constructor() {
        this.state = {
            name: "state"
        };
    }
    render() {
        return (
              <p>{this.state.name}</p>
        );
    }
}
// 需透過 setState 來更新
this.setState({    
    name: "update state"
});
而 React 16.8 後新增的 hook 使得 state 的套用更加便利
生成 state 不需再透過 constructor(),且更新 state 部分也更加簡潔
範例如下:
import React, { useState } from 'react';
function Example() {
  // 直接宣告state及其setState function
  const [name, setName] = useState('state');
  return (
    <div>
      <p>{name}</p>
      <button onClick={() => setName("update state")}>
        update name
      </button>
    </div>
  );
}
git rebase git merge 到底哪個好??
資料來源:
https://github.com/uberVU/react-guide/blob/master/props-vs-state.md
https://www.freecodecamp.org/news/react-js-for-beginners-props-state-explained/
https://reactjs.org/docs/hooks-state.html